﻿using APP.Log;
using APP.Win32;
using APP.Windows;
using Gma.System.MouseKeyHook;
using ScreenCapture.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ScreenCapture
{
    public class ScreenCaptureHelper : IDisposable
    {
        #region 第一界面操作  主要用于选中窗体 行程第一个识别框
        private IKeyboardMouseEvents _globalHook;
        private IntPtr _hwnd = IntPtr.Zero;
        private IntPtr _progMan;

        private double _getParentInaccuracy;
        MaskWindow maskWindow;

        public event Action<bool> HideManagerWindowEvent;
        public event Action ActiveManagerWindowEvent;

        ///// <summary>
        ///// 当前指定窗口的大小
        ///// </summary>
        //System.Drawing.Rectangle winRectangle;
        WindowInfo windoInfo;

        public WindowInfo ScreenCapture_SelectWindow()
        {
            if (maskWindow != null)
            {
                //说明已经开始录制了
                throw new Exception($"已经开始录制了");
            }

            _progMan = Win32Helper.GetTopWindow(Win32Helper.GetTopWindow(Win32Helper.FindWindow("ProgMan", null)));
            //if (windoInfo == null)
            //{
            //}
            windoInfo = new WindowInfo();
            ScaningWindows?.Clear();
            //windoInfo.FullScreenImageBitmap = WindowHelper.GetFullScreen();
            windoInfo.FullScreenImageBitmap = ScreenHelper.CapturePrimaryScreen();

            if (windoInfo.FullScreenImageBitmap == null)
            {
                return null;
            }
            //windoInfo.FullScreenImageBitmap.Save($"D:\\test\\{Guid.NewGuid()}.png");//用于debug
            //或者记录状态 ，当正在选择的时候不允许再点了
            maskWindow?.Close();
            maskWindow = null;

            InitGlobalHook();

            maskWindow = new MaskWindow();
            //maskWindow.ConfirmEvent += MaskWindow_ConfirmEvent;
            maskWindow.ConfirmCheckingEvent += MaskWindow_ConfirmCheckingEvent;
            maskWindow.ContinueSelectEvent += MaskWindow_ContinueSelectEvent;
            maskWindow.Width = 0;
            maskWindow.Height = 0;
            bool confirm = maskWindow.ShowDialog();

            if (ScaningWindows.Count > 0)
            {
                var lastWin = ScaningWindows.Pop();
                windoInfo.ProcessName = lastWin.ProcessName;
                windoInfo.WindowName = lastWin.WindowName;
            }
            ScaningWindows.Clear();

            DisposeHook();
            maskWindow?.Close();
            maskWindow = null;

            if (!confirm)
            {
                return null;
            }
            return windoInfo;
        }


        public System.Drawing.Rectangle WindowCapture()
        {
            var cawindow = new CaptureWindow();
            var backImage = cawindow.ShowDialog();
            var imageRect = cawindow.selectImageRect;
            return imageRect;
        }

        public System.Drawing.Bitmap WindowCapture(WindowInfo windoInfo)
        {
            var cawindow = new CaptureWindow(windoInfo);
            var backImage = cawindow.ShowDialog();
            if (backImage == null)
            {
                return null;
            }
            var imageRect = cawindow.selectImageRect;
            windoInfo.WindowsInnerRect = imageRect;
            windoInfo.ReLocateWindowInnerRect();
            //windoInfo.WindowsInnerRectForFullScreen = new System.Drawing.Rectangle(
            //     windoInfo.WindowRect.X + imageRect.X,
            //     windoInfo.WindowRect.Y + imageRect.Y,
            //     imageRect.Width,
            //     imageRect.Height);
            return backImage;
        }

        private void MaskWindow_ContinueSelectEvent()
        {
            //这里应该提供个直接取消
            InitGlobalHook();
        }

        private void MaskWindow_ConfirmCheckingEvent()
        {
            DisposeHook();
        }

        public void InitGlobalHook()
        {
            _globalHook = Hook.GlobalEvents();
            _globalHook.MouseMove += GlobalHook_MouseMove;
        }

        public void DisposeHook()
        {
            if (_globalHook != null)
            {
                _globalHook.MouseMove -= GlobalHook_MouseMove;
            }
            _globalHook?.Dispose();
            _globalHook = null;
        }

        /// <summary>
        /// 每次都会指定最上面的 iBotStudio，此时用作拿出上一次的
        /// </summary>
        Stack<WindowInfo> ScaningWindows = new Stack<WindowInfo>();

        private void GlobalHook_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            Log.Debug($"enter GlobalHook_MouseMove");
            Win32Helper.POINT point = new Win32Helper.POINT();
            Win32Helper.GetCursorPos(out point);

            IntPtr pointWinHwnd = Win32Helper.WindowFromPoint(point);

            if (pointWinHwnd == _hwnd || pointWinHwnd == _progMan)
            {
                Log.Debug($"pointWinHwnd:{pointWinHwnd.ToString("x")},_hwnd:{_hwnd.ToString("x")},_progMan:{_progMan.ToString("x")}");
                return;
            }

            int processId = 0;
            Win32Helper.GetWindowThreadProcessId(pointWinHwnd, out processId);
            System.Diagnostics.Process process = System.Diagnostics.Process.GetProcessById(processId);

            IntPtr oldPointWinHwnd = pointWinHwnd;

            pointWinHwnd = WindowHelper.GetParentWindow(pointWinHwnd, _getParentInaccuracy);

            System.Drawing.Rectangle rectangle = WindowHelper.GetWindowRectangle(pointWinHwnd);
            windoInfo.WindowRect = rectangle;
            windoInfo.WinTempIntPtr = pointWinHwnd;

            if (maskWindow == null)
            {
                Log.Error($"扫描窗体已注销");
                return;
            }

            maskWindow.Left = rectangle.X;
            maskWindow.Top = rectangle.Y;
            maskWindow.Width = rectangle.Width;
            maskWindow.Height = rectangle.Height;

            var ProcessName = WindowHelper.GetWndProcessName(pointWinHwnd);
            var WindowName = WindowHelper.GetWndWindowName(pointWinHwnd);
            windoInfo.ProcessName = ProcessName;
            windoInfo.WindowName = WindowName;
            var winName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString();
            if (!ProcessName.StartsWith("MinesweeperAutoScanDemo") && !ProcessName.StartsWith(winName))
            {
                ScaningWindows.Push(new WindowInfo()
                {
                    ProcessName = ProcessName,
                    WindowName = WindowName,
                    WindowRect = rectangle,
                });
            }
            Log.Debug($"processId:{processId.ToString("x")},pointWinHwnd:{oldPointWinHwnd.ToString("x")},MainWindowHandle:{pointWinHwnd.ToString("x")},WindowName:{WindowName},ProcessName:{ProcessName}");
        }

        #endregion

        public void RefreshWindowRecognizeEvent()
        {
            CloseAllWindow();
        }


        private void CloseAllWindow()
        {
            DisposeHook();
            maskWindow?.Close();
            maskWindow = null;

        }

        public void Dispose()
        {
            CloseAllWindow();
            DisposeHook();
            maskWindow?.Close();
            maskWindow = null;
        }
    }
}
